package com.example.nutritionmanager.conversationApi

import android.util.Log
import okhttp3.*
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources
import com.google.gson.Gson
import okhttp3.MediaType.Companion.toMediaType

class SSEClient {

    private val TAG = "SSEClient"
    private val APP_ID = "elvL0iKe4azCLne2H9CjDNGwgGxAj8wW"
    private val SECRET_KEY = "BbmgOJ3LLAdtSxEeAN4mdxcRnBLOkBVN"
    private val SOURCE = "elvL0iKe4azCLne2H9CjDNGwgGxAj8wW"
    private val API_URL = "https://agentapi.baidu.com/assistant/conversation?appId=" + APP_ID + "&secretKey=" + SECRET_KEY  // 替换为你的 API URL

    // 创建一个回调接口，用于将流式消息传递给界面层
    interface MessageListener {
        fun onAppendMessage(text: String)
        fun onFinish()
    }
    /**
     * 创建请求 JSON 字符串
     */
    private fun createRequestJson(inputText: String): String {
        val value = RequestBodyModel.Value(inputText)
        val content = RequestBodyModel.Content("text", value)
        val message = RequestBodyModel.Message(content)
        val requestBodyModel = RequestBodyModel(APP_ID, SECRET_KEY, SOURCE, message)

        // 使用 Gson 将请求体对象转为 JSON 字符串
        val gson = Gson()
        return gson.toJson(requestBodyModel)
    }

    /**
     * 处理服务器流式响应
     */
    private fun handleStreamResponse(responseBody: String, listener: MessageListener) {
        val gson = Gson()
        val event = gson.fromJson(responseBody, Event::class.java)

        event?.data?.message?.content?.firstOrNull()?.data?.text?.let { text ->
            Log.d(TAG, "Received message: $text")
            listener.onAppendMessage(text)  // 通知界面层有新消息


            // 在 UI 线程更新
            // 你需要根据你的 UI 代码更新 UI 组件，这里用 Log.d 示意
            // 例如，如果你是更新 TextView，可以用 runOnUiThread 执行 UI 更新操作
            // runOnUiThread {
            //     resultTextView2.append(text)
            // }
        }

        // 判断是否完成接收
        event?.data?.message?.endTurn?.let { isEndTurn ->
            if (isEndTurn) {
                Log.d(TAG, "Message received completely.")
                listener.onFinish()
            }
        }
    }

    /**
     * 发起 SSE 请求
     */
    fun startSSERequest(inputText: String, listener: MessageListener) {
        val client = OkHttpClient()

        // 创建请求体
        val jsonRequestBody = createRequestJson(inputText)
        val body = RequestBody.create("application/json".toMediaType(), jsonRequestBody)

        // 创建请求
        val request = Request.Builder()
            .url(API_URL)
            .post(body)
            .build()

        val eventSourceListener = object : EventSourceListener() {
            override fun onOpen(eventSource: EventSource, response: Response) {
                super.onOpen(eventSource, response)
                Log.d(TAG, "SSE connection opened.")
            }

            override fun onEvent(
                eventSource: EventSource,
                id: String?,
                type: String?,
                data: String
            ) {
                super.onEvent(eventSource, id, type, data)
                Log.d(TAG, "Received message: $data")
                handleStreamResponse(data, listener)  // 处理流式数据
            }

            override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
                super.onFailure(eventSource, t, response)
                Log.e(TAG, "SSE connection failed", t)
            }

        }

        // 使用 EventSources 创建 EventSource 实例
        val factory = EventSources.createFactory(client)

        // 使用 factory 创建 EventSource
        factory.newEventSource(request, eventSourceListener)
    }
}
